<template>
  <div class="app-container">

    <el-card class="box-card">
      <h3>商品介绍</h3>
      <el-form ref="goods" :rules="rules" :model="goods" label-width="150px">
        <el-form-item label="商品简介" prop="brief">
          <el-input v-model="goods.brief"/>
        </el-form-item>

        <el-form-item label="商品名称" prop="name">
          <el-input v-model="goods.name"/>
        </el-form-item>

        <el-form-item label="专柜价格" prop="counterPrice">
          <el-input v-model="goods.counterPrice" placeholder="0.00">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>

        <el-form-item label="零售价格" prop="retailPrice">
          <el-input v-model="goods.retailPrice" placeholder="0.00">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>

        <el-form-item label="商品排序" prop="sortOrder">
          <el-input v-model="goods.sortOrder" placeholder=""/>
        </el-form-item>

        <el-form-item label="商品单位" prop="unit">
          <el-input v-model="goods.unit" placeholder="件 / 个 / 盒 / 桶 ..."/>
        </el-form-item>

        <el-form-item label="商品分类" prop="categoryId">
          <el-select v-model="goods.categoryId" clearable>
            <el-option v-for="item in brandList" :key="item.categoryId" :label="item.name" :value="item.categoryId"/>
          </el-select>
        </el-form-item>

        <el-form-item label="商品票种类" prop="type">
          <el-select v-model="goods.type" clearable>
            <el-option v-for="item in typeOptions" :key="item.dictValue" :label="item.dictLabel"
                       :value="item.dictValue"/>
          </el-select>
        </el-form-item>

        <!--       多图 -->
        <el-form-item label="图片">
          <el-upload
            :action="uploadImgUrl"
            :limit="6"
            :headers="headers"
            :on-exceed="uploadOverrun"
            :on-success="handleGalleryUrl"
            :on-remove="handleRemove"
            multiple
            accept=".jpg,.jpeg,.png,.gif"
            list-type="picture-card"
          >
            <i class="el-icon-plus"/>
          </el-upload>
        </el-form-item>

        <el-form-item label="商品详情" style="height: 260px;">
          <Editor v-model="goods.detail"/>
        </el-form-item>

      </el-form>
    </el-card>

    <el-card class="box-card">
      <h3>商品规格</h3>
      <el-row :gutter="20" type="flex" align="middle" style="padding:20px 0;">
        <el-col :span="10">
          <el-radio-group v-model="multipleSpec" @change="specChanged">
            <el-radio-button :label="false">默认标准规格</el-radio-button>
            <el-radio-button :label="true">多规格支持</el-radio-button>
          </el-radio-group>
        </el-col>
        <el-col v-if="multipleSpec" :span="10">
          <el-button :plain="true" type="primary" @click="handleSpecificationShow">添加</el-button>
        </el-col>
      </el-row>

      <el-table :data="specifications">
        <el-table-column property="specification" label="规格名"/>
        <el-table-column property="value" label="规格值">
          <template slot-scope="scope">
            <el-tag type="primary">
              {{ scope.row.value }}
            </el-tag>
          </template>
        </el-table-column>
        <!--        <el-table-column property="picUrl" label="规格图片">-->
        <!--          <template slot-scope="scope">-->
        <!--            <img v-if="scope.row.picUrl" :src="scope.row.picUrl" width="40">-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column
          v-if="multipleSpec"
          align="center"
          label="操作"
          width="250"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button type="danger" size="normal" @click="handleSpecificationDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog :visible.sync="specVisiable" title="设置规格">
        <el-form
          ref="specForm"
          :rules="rules"
          :model="specForm"
          status-icon
          label-position="left"
          label-width="100px"
          style="width: 400px; margin-left:50px;"
        >
          <el-form-item label="规格名" prop="specification">
            <el-input v-model="specForm.specification"/>
          </el-form-item>
          <el-form-item label="规格值" prop="value">
            <el-input v-model="specForm.value"/>
          </el-form-item>
          <!--          <el-form-item label="规格图片" prop="picUrl">-->
          <!--            <el-upload-->
          <!--              :action="uploadPath"-->
          <!--              :show-file-list="false"-->
          <!--              :headers="headers"-->
          <!--              :on-success="uploadSpecPicUrl"-->
          <!--              class="avatar-uploader"-->
          <!--              accept=".jpg,.jpeg,.png,.gif"-->
          <!--            >-->
          <!--              <img v-if="specForm.picUrl" :src="specForm.picUrl" class="avatar">-->
          <!--              <i v-else class="el-icon-plus avatar-uploader-icon"/>-->
          <!--            </el-upload>-->
          <!--          </el-form-item>-->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="specVisiable = false">取消</el-button>
          <el-button type="primary" @click="handleSpecificationAdd">确定</el-button>
        </div>
      </el-dialog>
    </el-card>

    <el-card class="box-card">
      <h3>商品库存</h3>
      <el-table :data="products">
        <el-table-column property="value" label="货品规格">
          <template slot-scope="scope">
            <el-tag v-for="tag in scope.row.specifications" :key="tag">
              {{ tag }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column property="price" width="100" label="货品售价"/>
        <el-table-column property="number" width="100" label="货品数量"/>
        <el-table-column property="integral" width="100" label="货品积分兑换"/>
        <el-table-column align="center" label="操作" width="100" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="primary" size="normal" @click="handleProductShow(scope.row)">设置</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog :visible.sync="productVisiable" title="添加货品">
        <el-form
          ref="productForm"
          :model="productForm"
          status-icon
          label-position="left"
          label-width="100px"
          style="width: 400px; margin-left:50px;"
        >
          <el-form-item label="货品规格列" prop="specifications">
            <el-tag v-for="tag in productForm.specifications" :key="tag">
              {{ tag }}
            </el-tag>
          </el-form-item>
          <el-form-item label="货品售价" prop="price">
            <el-input v-model="productForm.price"/>
          </el-form-item>
          <el-form-item label="货品数量" prop="number">
            <el-input v-model="productForm.number"/>
          </el-form-item>
          <el-form-item label="货品积分兑换" prop="integral">
            <el-input v-model="productForm.integral"/>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="productVisiable = false">取消</el-button>
          <el-button type="primary" @click="handleProductEdit">确定</el-button>
        </div>
      </el-dialog>
    </el-card>

    <div class="op-container">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handlePublish">上架</el-button>
    </div>

  </div>
</template>

<script>
  import { getdeptlist, getcategoryList, goodsCreate, publishGoods, listCatAndBrand } from '@/api/goods'
  // import { createStorage, uploadPath } from '@/api/storage'
  // import Editor from '@tinymce/tinymce-vue'
  // import { MessageBox } from 'element-ui'
  import { getToken } from '@/utils/auth'
  import Editor from '@/components/Editor'

  export default {
    name: 'GoodsCreate',
    components: { Editor },

    data() {
      return {
        typeOptions: [], //1 电子水票 2 纸质水票  3水  typeOptions
        brandList: [],  //分类数组
        //商品简介
        goods: {
          type: null, //商品种类
          brief: '',//商品简介
          categoryId: null,//所属种类
          counterPrice: null,//专柜价格
          delFla: '',//商品状态
          detail: '',//商品详情
          isOnSale: 1,//商品是否上下架
          name: '',//商品名称
          retailPrice: null,//零售价格
          sortOrder: null,//商品排序
          unit: null//商品单位
        },
        rules: {
          type: [{ required: true, message: '商品种类不能为空', trigger: 'blur' }], //商品种类
          brief: [{ required: true, message: '商品简介不能为空', trigger: 'blur' }],//商品简介
          categoryId: [{ required: true, message: '所属种类不能为空', trigger: 'blur' }],//所属种类
          counterPrice: [{ required: true, message: '专柜价格不能为空', trigger: 'blur' }],//专柜价格
          delFla: [{ required: true, message: '商品状态不能为空', trigger: 'blur' }],//商品状态
          name: [{ required: true, message: '商品名称不能为空', trigger: 'blur' }],//商品名称
          retailPrice: [{ required: true, message: '零售价格不能为空', trigger: 'blur' }],//零售价格
          sortOrder: [{ required: true, message: '商品单位不能为空', trigger: 'blur' }],//商品单位
          unit: [{ required: true, message: '商品单位不能为空', trigger: 'blur' }]//商品单位
        },
        uploadImgUrl: process.env.VUE_APP_BASE_API + '/common/upload', // 上传的图片服务器地址
        headers: {
          Authorization: 'Bearer ' + getToken()
        },
        goodsImgs: [// {//   "imgUrl": "string"  //图片地址// }
        ],
        specVisiable: false,
        specForm: { specification: '', value: '' },
        multipleSpec: false,
        specifications: [{ specification: '规格', value: '标准' }],
        productVisiable: false,
        productForm: { id: 0, specifications: [], price: 0.00, number: 0, integral: 0 },   //设置进去添加货品对话框
        products: [{ id: 0, specifications: ['标准'], price: 0.00, number: 0, integral: 0 }],
        attributeVisiable: false,
        attributeForm: { attribute: '', value: '' },
        attributes: [],

        uploadPath: '',
        newKeywordVisible: false,
        newKeyword: '',
        keywords: [],
        categoryList: []
      }
    },
    computed: {},
    watch: {
      goods: {
        handler: function(newval, oldval) {
          console.log(newval)
        },
        deep: true//对象内部的属性监听，也叫深度监听
      },
      goodsImgs: {
        handler: function(newval, oldval) {
          console.log(newval)
        },
        deep: true//对象内部的属性监听，也叫深度监听
      }
    },
    created() {
      getcategoryList().then(res => {
        console.log('查询分类列表', res)
        this.brandList = res.data
      })

      //1 电子水票 2 纸质水票  3水  typeOptions
      this.getDicts('sys_water_type').then(response => {
        this.typeOptions = response.data
      })
    },

    methods: {
      //图片相关接口
      uploadOverrun: function() {
        this.$message({
          type: 'error',
          message: '上传文件个数超出限制!最多上传6张图片!'
        })
      },
      handleGalleryUrl(response, file, fileList) {
        // console.log(response, file, fileList)
        if (response.code === 200) this.goodsImgs.push({ imgUrl: response.fileName })

      },
      handleRemove: function(file, fileList) {
        for (var i = 0; i < this.goodsImgs.length; i++) {
          this.goodsImgs.splice(i, 1)
        }
      },

      //底部取消按钮
      handleCancel: function() {
        this.$router.push({ path: '/goods/list' })
      },
      //底部上传接口
      handlePublish: function() {
        this.$refs[`goods`].validate((valid) => {
          if (valid) {

            var goodsProducts = this.products

            var goodsSpecifications = this.specifications
            if (goodsProducts.length > 0) {
              goodsProducts.forEach((items, i) => {
                delete items.id
              })
            }
            const finalGoods = {
              goods: this.goods,
              goodsImgs: this.goodsImgs,
              goodsSpecifications: goodsSpecifications,
              goodsProducts: goodsProducts,
              attributes: this.attributes
            }

            console.log('底部用于显示数据', finalGoods)

            //封装上传
            var postObj = {
              goods: this.goods,
              goodsImgs: this.goodsImgs,
              goodsProducts: goodsProducts,
              goodsSpecifications: goodsSpecifications
            }
            console.log('底部用于上传数据', postObj)

            if (postObj.goodsProducts.length == 0 || postObj.goodsProducts.length == 0) {
              this.$message.error('请添加商品规格和库存！')
              return false
            } else {
              goodsCreate(postObj).then(response => {
                if (response.code === 200) {
                  this.$notify.success({
                    title: '成功',
                    message: '创建成功'
                  })
                  this.$router.push({ path: '/goods/list' })
                }
              })
            }

            // goodsCreate(postObj).then(response => {
            //   if (response.code === 200) {
            //     this.$notify.success({
            //       title: '成功',
            //       message: '创建成功'
            //     })
            //     this.$router.push({ path: '/goods/list' })
            //   }
            // })

          } else {
            console.log('error submit!!')
            return false
          }
        })
      },

      init: function() {
        listCatAndBrand().then(response => {
          this.categoryList = response.data.data.categoryList
          this.brandList = response.data.data.brandList
        })
      },
      handleCategoryChange(value) {
        this.goods.categoryId = value[value.length - 1]
      },

      handleClose(tag) {
        this.keywords.splice(this.keywords.indexOf(tag), 1)
        this.goods.keywords = this.keywords.toString()
      },
      showInput() {
        this.newKeywordVisible = true
        this.$nextTick(_ => {
          this.$refs.newKeywordInput.$refs.input.focus()
        })
      },
      handleInputConfirm() {
        const newKeyword = this.newKeyword
        if (newKeyword) {
          this.keywords.push(newKeyword)
          this.goods.keywords = this.keywords.toString()
        }
        this.newKeywordVisible = false
        this.newKeyword = ''
      },
      uploadPicUrl: function(response) {
        this.goods.picUrl = response.data.url
      },

      specChanged: function(label) {
        if (label === false) {
          this.specifications = [{ specification: '规格', value: '标准' }]
          this.products = [{ id: 0, specifications: ['标准'], price: 0.00, number: 0, integral: 0 }]
        } else {
          this.specifications = []
          this.products = []
        }
      },
      uploadSpecPicUrl: function(response) {
        this.specForm.picUrl = response.data.url
      },
      handleSpecificationShow() {
        this.specForm = { specification: '', value: '' }
        this.specVisiable = true
      },
      handleSpecificationAdd() {
        var index = this.specifications.length - 1
        for (var i = 0; i < this.specifications.length; i++) {
          const v = this.specifications[i]
          if (v.specification === this.specForm.specification) {
            if (v.value === this.specForm.value) {
              this.$message({
                type: 'warning',
                message: '已经存在规格值:' + v.value
              })
              this.specForm = {}
              this.specVisiable = false
              return
            } else {
              index = i
            }
          }
        }

        this.specifications.splice(index + 1, 0, this.specForm)
        this.specVisiable = false

        this.specToProduct()
      },
      handleSpecificationDelete(row) {
        const index = this.specifications.indexOf(row)
        this.specifications.splice(index, 1)
        this.specToProduct()
      },
      specToProduct() {
        if (this.specifications.length === 0) {
          return
        }
        // 根据specifications创建临时规格列表
        var specValues = []
        var spec = this.specifications[0].specification
        var values = []
        values.push(0)

        for (var i = 1; i < this.specifications.length; i++) {
          const aspec = this.specifications[i].specification

          if (aspec === spec) {
            values.push(i)
          } else {
            specValues.push(values)
            spec = aspec
            values = []
            values.push(i)
          }
        }
        specValues.push(values)

        // 根据临时规格列表生产货品规格
        // 算法基于 https://blog.csdn.net/tyhj_sf/article/details/53893125
        var productsIndex = 0
        var products = []
        var combination = []
        var n = specValues.length
        for (var s = 0; s < n; s++) {
          combination[s] = 0
        }
        var index = 0
        var isContinue = false
        do {
          var specifications = []
          for (var x = 0; x < n; x++) {
            var z = specValues[x][combination[x]]
            specifications.push(this.specifications[z].value)
          }
          products[productsIndex] = {
            id: productsIndex,
            specifications: specifications,
            price: 0.00,
            number: 0
          }
          productsIndex++

          index++
          combination[n - 1] = index
          for (var j = n - 1; j >= 0; j--) {
            if (combination[j] >= specValues[j].length) {
              combination[j] = 0
              index = 0
              if (j - 1 >= 0) {
                combination[j - 1] = combination[j - 1] + 1
              }
            }
          }
          isContinue = false
          for (var p = 0; p < n; p++) {
            if (combination[p] !== 0) {
              isContinue = true
            }
          }
        } while (isContinue)

        this.products = products
      },
      handleProductShow(row) {
        this.productForm = Object.assign({}, row)
        this.productVisiable = true
      },
      uploadProductUrl: function(response) {
        // this.productForm.url = response.data.url
      },
      handleProductEdit() {
        for (var i = 0; i < this.products.length; i++) {
          const v = this.products[i]
          if (v.id === this.productForm.id) {
            this.products.splice(i, 1, this.productForm)
            break
          }
        }
        this.productVisiable = false
      },
      handleAttributeShow() {
        this.attributeForm = {}
        this.attributeVisiable = true
      },
      handleAttributeAdd() {
        this.attributes.unshift(this.attributeForm)
        this.attributeVisiable = false
      },
      handleAttributeDelete(row) {
        const index = this.attributes.indexOf(row)
        this.attributes.splice(index, 1)
      }
    }
  }
</script>


<style>
  .el-card {
    margin-bottom: 10px;
  }

  .el-tag + .el-tag {
    margin-left: 10px;
  }

  .input-new-keyword {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }

  .avatar-uploader .el-upload {
    width: 145px;
    height: 145px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }

  .avatar {
    width: 145px;
    height: 145px;
    display: block;
  }
</style>

